package com.roy.minimq.namesrv.applicaton;

import com.roy.minimq.common.namesrv.NamesrvConfig;
import com.roy.minimq.remoting.domain.nettyserver.NettyServerConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author ：楼兰
 * @date ：Created in 2021/8/9
 * @description:
 **/

public class NamesrvStartup{

    private static Logger logger = LoggerFactory.getLogger(NamesrvStartup.class);

    public static void main(String[] args) {
        try{
            NamesrvController controller = createNamesrvController();
            logger.info(">>> nameserver starting");
            final boolean initialize = controller.initialize();
            if(!initialize){

                System.exit(-1);
            }

            //服务关闭钩子
            Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
                private volatile boolean hasShutdown = false;
                private AtomicInteger shutdownTimes = new AtomicInteger(0);

                @Override
                public void run() {
                    synchronized (this) {
                        logger.info("Shutdown hook was invoked, {}", this.shutdownTimes.incrementAndGet());
                        if (!this.hasShutdown) {
                            this.hasShutdown = true;
                            long beginTime = System.currentTimeMillis();
                            controller.shutdown();
                            long consumingTimeTotal = System.currentTimeMillis() - beginTime;
                            logger.info("Shutdown hook over, consuming total time(ms): {}", consumingTimeTotal);
                        }
                    }
                }
            }
                    ,"BrokerShutDownHookThread"));
            controller.start();
            logger.info(">>> nameserver started ");
        }catch (Throwable e){
            e.printStackTrace();
            System.exit(-1);
        }
    }

    public static NamesrvController createNamesrvController(){
        final NamesrvConfig namesrvConfig = new NamesrvConfig();
        final NettyServerConfig nettyServerConfig = new NettyServerConfig();
        nettyServerConfig.setListenPort(9876);

        NamesrvController controller = new NamesrvController(namesrvConfig,nettyServerConfig);
        return controller;
    }

    public void shutdown(NamesrvController controller){
        controller.shutdown();
    }
}
